package com.windaka.elements.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.windaka.elements.annotation.RepeatSubmit;
import com.windaka.elements.utils.HttpHelper;
import com.windaka.elements.utils.RedisCommon;
import com.windaka.elements.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wangning
 * @version 1.0
 * Create by 2024/2/23 15:56
 */
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {

    private static final String KEY = "idempotent:";

    @Autowired
    private RedisCommon redisCache;

    @Override
        public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation)
    {
        // 请求地址（作为存放cache的key值）目前放的是账号，也可以放token
        String username = SecurityUtils.getUsername();
//        String userToken = SecurityUtils.getUserToken();
        String url = KEY + request.getRequestURI() + "-" + username;

        Object sessionObj = redisCache.getObj(url);
        if (sessionObj != null) {
            return true;
        }
        redisCache.setAllObj(url, "", annotation.interval(), TimeUnit.MILLISECONDS);
        return false;
    }
}
